﻿using Newtonsoft.Json;
using System.IO;

namespace Loaf.Tools
{
    public class JsonTool
    {
        public static T ReadJson<T>(string fileName) where T : new()
        {
            try
            {
                var path = fileName + ".json";

                if (!Directory.Exists("./Resources"))
                {
                    Directory.CreateDirectory("./Resources");
                }
                if (!File.Exists("./Resources/" + path))
                {
                    File.Create("./Resources/" + path).Close();
                }
                var content = File.ReadAllText("./Resources/" + path);

                T result = JsonConvert.DeserializeObject<T>(content);
                return result == null ? new T() : result;
            }
            catch
            {
                return new T();
            }
        }

        public static void WriteJson<T>(T obj, string fileName)
        {
            try
            {
                var path = fileName + ".json";

                if (!Directory.Exists("./Resources"))
                {
                    Directory.CreateDirectory("./Resources");
                    if (!File.Exists("./Resources/" + path))
                    {
                        File.Create("./Resources/" + path).Close();
                    }
                }
                var content = JsonConvert.SerializeObject(obj);

                File.WriteAllText("./Resources/" + path, content);

            }
            catch
            {
                return;
            }
        }

    }
}
